<?php
/**
 * Created by PhpStorm.
 * User: 马萍
 * Date: 2017/11/22
 * Time: 22:05
 */

namespace Admin\Controller;
use Admin\Logic\MemberLogic;
use Admin\Logic\OrderLogic;
use Admin\Logic\FoodLogic;
use Admin\Logic\StockLogic;

class OrderController extends CommonController
{

    //订单列表
    public function index()
    {

        // 获取订单列表
        $order = OrderLogic::getAll();
        $this->assign(['order'=>$order]);
        $this->display();
    }

    /**
     * 获取订单数据
     * @return bool
     */
    public function get()
    {



        $token = 'yibmnt1511770872';
        $suc_id = [];

        $token = I('post.token','', 'htmlspecialchars');

        $cid=1100;
        $startTime = OrderLogic::getMaxTime();
        $tm=time();

        $str=md5($tm.'jdgldd102ssssss'.'yibmnt1511770872'.$cid);

        $url = "http://vip.vcdes.com/index.php?g=Webs&m=Vdingdan&a=index&token=$token&cid=$cid&str=$str&tm=$tm&st[]=".$startTime."&st[]=".$tm."";

        $result = http_request($url); //获取源数据

        // $result = mb_substr($result, 5);   //去除源数据的<pre>标签
        if(!$result){
            return false;
        }

        $data = json_decode($result, true); //转数组

        foreach ($data as $key => &$value) {
            $value['info'] = unserialize($value['info']);  //把菜谱反序列化回来成数组
        }



        // 拼装数据
        try{
            $order = '';
            // 清除库存不足的session
            if(session('?stock')){
                session('stock',null);
            }
            $food_loss = 0;
            $food_sale = 0;
            foreach ($data as $key=>$val){
                // 判断是否已存在此订单
                $res = M('Order')
                    ->where(['order_id'=>$val['orderid']])
                    ->field(['id'])
                    ->find();
                if(!empty($res)){
                    continue;
                }

                $order = [
                    'order_id'        => $val['orderid'],                     //订单编号
                    'order_store'     => $val['cid'],      //分店id
                    'customer_name'   => $val['name'],       //客户姓名
                    'order_name'   => $val['tableid'],       //桌号
                    'order_total'     => $val['price'],                  //订单总金额
                    'order_pay'       => '现金',           //支付方式
                    'is_pay'          => '已支付',              //支付状态
                    'reserve_state'   => '预约成功',       //预约状态
                    'reserve_time'    => date("Y-m-d H:i:s",$val['time']),        //预约时间
                    'customer_mobile' => $val['tel'],     //客户手机号
                    'order_num'       => '1',           //就餐人数
                    'token'           => $val['token'],               //商家用户
                    'pinglun'         => $val['pinglun'],
                    'plxj'            => $val['plxj'],
                    'created_at'      => getDateTime(),
                ];

                // 开启事务
                $model = M();
                $model->startTrans();
                $flag = true;

                // 添加订单
                $order_id = D('Order')->add($order);
                if($order_id === false){
                    $flag = false;
                }

                // 添加订单详情(菜谱)
                $info = [];
                $food_id = [];
                
                foreach ($val['info'] as $k=>$v){
                    $foodData = D('food')->where(['name'=>$v['name']])->field(['id','loss'])->find();
                    $foodId = $foodData['id'];
                    $food_id[] = $foodId;
                    $info[] = [
                        'order_id'  => $order_id,
                        'food_id'   => $foodId,
                        'spec'      => empty($v['spec'])?'大':mb_substr($v['spec'],0,1),
                        'num'=>$v['num']
                    ];
                    // 计算出菜谱库存消耗
                    $food_loss_v  = FoodLogic::getStockLoss($foodId,$v['num']) + json_decode($foodData['loss'], true)['大'];
                    $food_loss += $food_loss_v;


                    // 计算出菜谱销售价
                    $food_sale_v = FoodLogic::getFoodPrice($foodId);
                    $food_sale += $food_sale_v;
                }

                // 添加库存详情
                $data = FoodLogic::getOrderFoodStock($food_id);
                $res = D('Order')->where(['id'=>$order_id])->save(['stock_detail'=>json_encode($data)]);

                if($res === false){
                    $flag = false;
                }

                // 添加订单详情的记录
                $detail = D('OrderDetail')->addAll($info);
                if($detail === false){
                    $flag = false;
                }
               
                // 给订单的成本价和销售价赋值
                $food_loss_sale_data = [
                    'order_cost' => $food_loss,
                    'order_sale' => $food_sale,
                ];
                $food_sale = 0;
                $food_loss = 0;
                $res = D('Order')
                    ->where(['id'=>$order_id])
                    ->save($food_loss_sale_data);
                if($res === false){
                    $flag = false;
                }


                // 减少库存，更新库存流水
                //获取菜谱用了多少材料
                $food = FoodLogic::getFindAll($food_id);
                //更新库存明细表
                $stock_detail = StockLogic::updateDetailOrder($food, $order_id);
                if($stock_detail  === false){
                    $flag = false;
                }




                // 根据传过来的桌号，找到对应餐桌和员工,并添加到订单中
                $table_id = D('Table as t')
                    ->where(['table_name'=>$val['tableid']])
                    ->join('left join food_member as m on t.member_id=m.id')
                    ->field(['t.*,m.nickname'])
                    ->find();
                $data = [
                    'person_id'=>$table_id['member_id'],     //餐桌负责员工
                    'person_name'=>$table_id['nickname']     //员工姓名
                ];
                $res = D('Order')
                    ->where(['id'=>$order_id])
                    ->save($data);
                if($res === false){
                    $flag = false;
                }

                //提交
                if ($flag) {
                    $model->commit();
                    $suc_id[] = $val['id'];
                } else {
                    $model->rollback();
                }

            }

            if(session('?stock')){
                $msg = session('stock');
            } else {
                $msg = '';
            }
            echo  json_encode(['order_id'=>$suc_id,'msg'=>$msg]);

        } catch (\Exception $e){
            return false;
        }



    }

    /**
     * 订单报表统计
     */
    public function form()
    {

        // 时间条件（默认推前7天）
        $day = 7;
        // 推前15天，30天
        if(I('post.day') != ''){
            $day = I('post.day');
        }
        $nowTime = date('Y-m-d').' 23:59:59';
        $startTime = date("Y-m-d", strtotime("-".$day." day")).' 00:00:00';

        // 时间段条件
        if(I('post.start') && I('post.end')){
            $nowTime = I('post.start').' 00:00:00';
            $startTime = I('post.end').' 23:59:59';
            if(strtotime($nowTime) < strtotime($startTime)){
                $a = $nowTime;
                $nowTime = $startTime;
                $startTime = $a;
            }


        }

        // 根据时间分组
        $dayData = OrderLogic::getOrderGroupTime($startTime,$nowTime);

        // 总计初始化
        $money_total = 0;
        $order_number = 0;
        $stock_loss_total = 0;
        $money = 0;

        foreach ($dayData as $k=>$v)
        {

            // 查询这天的所有订单数据
            $order_food = OrderLogic::getDayOrderDetail($v['时间']);

            // 根据菜谱id 到菜谱i详情里找到库存算出库存损耗


            $stock_loss = 0;
            $loss = 0;
            foreach ($order_food as $food_k=>$food_v)
            {

                // 计算出每个菜谱的库存损耗
                $order_food[$food_k]['stock_loss'] = FoodLogic::getStockLoss($food_v['food_id'],$food_v['num']);
                $stock_loss += $order_food[$food_k]['stock_loss'];

                // 根据规格得到损耗
                switch ($food_v['spec']){
                    case '大':
                        $order_food[$food_k]['loss'] = json_decode($food_v['loss'], true)['大'];
                        break;

                    case '中':
                        $order_food[$food_k]['loss'] = json_decode($food_v['loss'], true)['中'];
                        break;

                    case '小':
                        $order_food[$food_k]['loss'] = json_decode($food_v['loss'], true)['小'];
                        break;
                }
                $loss += $order_food[$food_k]['loss'];


            }



            $dayData[$k]['库存损耗'] = $stock_loss;
            $dayData[$k]['损耗'] = $loss;
            // 利润 = 订单金额 - 库存损耗 - 损耗
            $dayData[$k]['利润'] = ($dayData[$k]['订单金额']) - ($dayData[$k]['库存损耗']) - ($dayData[$k]['损耗']);

            // 总计
            $money_total += $dayData[$k]['订单金额'];
            $order_number += $dayData[$k]['订单总数'];
            $stock_loss_total += $dayData[$k]['库存损耗'];
            $money += $dayData[$k]['利润'];

        }



        $this->assign(['order'=>$dayData]);
        $this->assign(['total'=>[
            '金额'        =>$money_total,
            '订单数'      =>$order_number,
            '库存损耗'    =>$stock_loss_total,
            '利润'        =>$money
        ]]);
        $this->assign(['time'=>[
            'start'=>I('post.start'),
            'end'=>I('post.end')
        ]]);
        $this->assign(['day'=>$day]);
        $this->display();
    }

    public function stockDetail()
    {
        $id = I('get.id');
        // 获取订单所有菜谱
        $food = D('OrderDetail as d')
            ->where(['d.order_id'=>$id])
            ->join('left join food_food as f on d.food_id=f.id')
            ->field(['d.food_id,f.name'])
            ->select();



        $res = D('Order')
            ->where(['id'=>$id])
            ->field(['stock_detail'])
            ->find();
//        dump(json_decode($res['stock_detail']));
        $this->assign(['food'=>$food]);
        $this->assign(['data'=>json_decode($res['stock_detail'], true)]);
        $this->display();
    }

    //订单添加页面
    public function add()
    {
        $id = I('get.id')? I('get.id') : '';
        $orders = array();
        if ($id != '') {
            $orders = OrderLogic::getOne($id);
        }
        $foods = FoodLogic::getAll();
        
        // 获取所有员工
        $member = MemberLogic::getAll([], 'id,nickname');

        $this->assign(['foods'=>$foods,'orders'=>$orders,'member'=>$member]);
        $this->display();
    }

    //添加订单
    public function store()
    {
        $this->checkPost();
        $order_id = date('Y').date('m').date('d').rand(0000, 9999);
        //先获取菜品金额
        $order_total = FoodLogic::getOrderTotal(I('food_id'));
        $param = [
            'order_id'        => $order_id,                     //订单编号
            'order_store'     => I('post.order_store', 0),      //分店id
            'order_name'      => I('post.order_name', 0),       //餐桌号码
            'customer_name'   => I('post.customer_name'),       //客户姓名
            'order_total'     => $order_total,                  //订单总金额
            'order_pay'       => I('post.order_pay'),           //支付方式
            'is_pay'          => I('post.is_pay'),              //支付状态
            'reserve_state'   => I('post.reserve_state'),       //预约状态
            'reserve_time'    => I('post.reserve_time'),        //预约时间
            'customer_mobile' => I('post.customer_mobile'),     //客户手机号
            'order_num'       => I('post.order_num'),           //就餐人数
            'token'           => I('post.token'),               //商家用户
            'food_id'         => I('post.food_id'),
            'person_id'       => I('post.person_id')
        ];

        $result = OrderLogic::create($param);
        if ($result > 0) {
            return $this->ajaxSuccess();
        } else {
            return $this->ajaxError('添加失败，请重试');
        }

    }

    public function delete()
    {
        $id = I('get.id', 0, 'intval');

        $data = OrderLogic::delete($id);

        if (json_decode($data,true)['code'] > 0) {
            return $this->ajaxSuccess();
        } else {
            return $this->ajaxError(json_decode($data,true)['errorMsg']);
        }
    }


}